package com.zhouwj.utils.HTTPUtils;

import android.content.Context;

import com.silverknife.volley.AuthFailureError;
import com.silverknife.volley.Request;
import com.silverknife.volley.RequestQueue;
import com.silverknife.volley.Response;
import com.silverknife.volley.VolleyError;
import com.silverknife.volley.toolbox.JsonObjectRequest;
import com.silverknife.volley.toolbox.StringRequest;
import com.silverknife.volley.toolbox.Volley;
import com.zhouwj.utils.MyApplication;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhouwj on 2017/2/21.
 */

public class HttpUtilsWithVolley {
    public static void get(String host, HashMap<String, String> params, String TAG, boolean useCache, final IVolleyHttpCallback volleyHttpCallback) {
        String url = getUrl(host, params);
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            volleyHttpCallback.onSuccess(new JSONObject(response));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                volleyHttpCallback.onFailed(error);
            }
        });
        stringRequest.addMarker(TAG);
        stringRequest.setShouldCache(useCache);
        MyApplication.getRequestQueue().add(stringRequest);
    }

    public void post(String host, final HashMap<String,String> params, String TAG, boolean useCache, final IVolleyHttpCallback volleyHttpCallback){
        StringRequest stringRequest = new StringRequest(Request.Method.POST, host,new Response.Listener<String>(){

            @Override
            public void onResponse(String response) {
                try {
                    volleyHttpCallback.onSuccess(new JSONObject(response));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                volleyHttpCallback.onFailed(error);
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }
        };
        stringRequest.setShouldCache(useCache);
        stringRequest.addMarker(TAG);
        MyApplication.getRequestQueue().add(stringRequest);
    }

    public void postWithJSON(String host, final HashMap<String,String> params, String TAG, boolean useCache, final IVolleyHttpCallback volleyHttpCallback){
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, host, changToJSON(params), new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                volleyHttpCallback.onSuccess(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                volleyHttpCallback.onFailed(error);
            }
        });
        jsonObjectRequest.setShouldCache(useCache);
        jsonObjectRequest.addMarker(TAG);
        MyApplication.getRequestQueue().add(jsonObjectRequest);
    }

    public static void cancle(String TAG){
        MyApplication.getRequestQueue().cancelAll(TAG);
    }

    private static JSONObject changToJSON(HashMap<String,String> params){
        JSONObject object = new JSONObject();
        for (Map.Entry entry:params.entrySet()){
            try {
                object.put(entry.getKey().toString(),entry.getValue().toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return object;
    }

    private static String getUrl(String host, HashMap<String, String> params) {
        StringBuilder url = new StringBuilder();
        if (!host.startsWith("http://")) {
            url.append("http://");
        }
        url.append(host);
        if (!host.endsWith("?")) {
            url.append("?");
        }
        for (int i = 0; i < params.size(); i++) {
            Map.Entry entry = params.entrySet().iterator().next();
            url.append(entry.getKey() + "=" + entry.getValue());
            url.append("&");
        }
        url = url.deleteCharAt(url.length() - 1);
        return url.toString();
    }
}
